package middleware

import (
	"go-project/common"
	"go-project/common/base/resp"
	"strconv"

	"github.com/gin-gonic/gin"
)

func CasbinMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		user := GetUser(c)

		//a := fileadapter.NewAdapter("config/policy.csv")
		//e, err := casbin.NewEnforcer(m, a)
		//if err != nil {
		//	resp.Error(c, err.Error())
		//	c.Abort()
		//	return
		//}

		err := common.ENFORCER.LoadPolicy()
		if err != nil {
			resp.Error(c, err.Error())
			c.Abort()
			return
		}
		check, err := common.ENFORCER.Enforce(strconv.FormatUint(uint64(user.ID), 10), c.Request.URL.Path, c.Request.Method)
		if err != nil {
			resp.Error(c, err.Error())
			c.Abort()
			return
		}
		if !check {
			resp.BadRequest(c, "无权访问")
			c.Abort()
			return
		}
		c.Next()
	}
}
